package net.bxx2004.pandalibloader;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import static net.bxx2004.pandalibloader.ServerUtils.*;

public class PandaLibPlayer {
    private Object player;
    public PandaLibPlayer(Object player){

        this.player = player;
    }
    public void pluginMessage(String... message){
        if (server() == ServerType.BUNGEECORD){
            ProxiedPlayer p = (ProxiedPlayer) player;
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(b);
            try {
                for (String m : message){
                    out.writeUTF(m);
                }
            } catch (Exception e) {

            }
            p.sendData("Bukkit",b.toByteArray());
        }
        if (server() == ServerType.BUKKIT){
            Player p = (Player) player;
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(b);
            try {
                for (String m : message){
                    out.writeUTF(m);
                }
            } catch (Exception e) {

            }
            p.sendPluginMessage(Bukkit.getPluginManager().getPlugin("PandaLib"), "BungeeCord",b.toByteArray());
        }
    }
    /**
     * 把某个玩家连接到某个服务器
     * @param player 玩家名
     * @param serverName 服务器名
     */
    public void connect(Object player,String serverName){
        if (server() == ServerType.BUNGEECORD){
            ProxiedPlayer p = (ProxiedPlayer) player;
            ServerInfo server = ProxyServer.getInstance().getServerInfo(serverName);
            p.connect(server);
        }
        if (server() == ServerType.BUKKIT){
            Player p = (Player) player;
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(b);
            try {
                out.writeUTF("Connect");
                out.writeUTF(serverName);
            } catch (Exception e) {
            }
            p.sendPluginMessage(Bukkit.getPluginManager().getPlugin("PandaLib"), "BungeeCord", b.toByteArray());
        }
    }
    public void message(String... message){
        if (server() == ServerType.BUKKIT){
            Player p = (Player) player;
            for (String m : message){
                p.sendMessage(m.replaceAll("&","§"));
            }
        }
        if (server() == ServerType.BUNGEECORD){
            ProxiedPlayer p = (ProxiedPlayer) player;
            for (String m : message){
                p.sendMessage(m.replaceAll("&","§"));
            }
        }
    }
}
